package com.jtx.miaoah2.Cache;

import com.jtx.miaoah2.Common.RedisConstants;
import com.jtx.miaoah2.Model.goods.DO.SkGoodsSeckill;
import com.jtx.miaoah2.Model.order.DTO.CreateOrderDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 季台星
 * @Date 2023 07 25 09 37
 */
@Component
@Slf4j
public class GoodsTokenCache {
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 创建商品数量，每次预下单从这里库存-1
     * key 为 秒杀场次id + 商品 id达到唯一性
     * @param skGoodsSeckill
     */
    public void addToken(SkGoodsSeckill skGoodsSeckill) {
        redisTemplate.opsForValue().set(RedisConstants.GOODS_STOCK + skGoodsSeckill.getId() + "_" +skGoodsSeckill.getGoodsId(),
                skGoodsSeckill.getStockCount().toString(), 60, TimeUnit.HOURS);
    }
    public boolean hasStock(Long seckillId,Long goodsId){
        String key = RedisConstants.GOODS_STOCK + seckillId + "_" + goodsId;
        String goodsStock = redisTemplate.opsForValue().get(key);
        Integer stock = Integer.valueOf(goodsStock);
        if (stock <= 0){
            //已经没有库存，删除id
            redisTemplate.delete(key);
            return false;
        }
        return true;
    }
    public boolean tryGetToken(Long goodsId, Long seckillId){
        Long tokenNum = null;
        try {
            tokenNum = redisTemplate.opsForValue().decrement(RedisConstants.GOODS_STOCK + seckillId + "_" + goodsId);
        } catch (Exception e) {
            log.info("获取令牌发生异常,秒杀场次id为：{},商品id为：{}",seckillId,goodsId);
            return false;
        }
        if (tokenNum <= 0){
            return false;
        }
        return true;
    }

    public boolean addUserToken(CreateOrderDto createOrderDto) {
        Long seckillId = createOrderDto.getSeckillId();
        Long goodsId = createOrderDto.getGoodsId();
        String goodsToken = RedisConstants.GOODS_TOKEN;
        String userToken = RedisConstants.USER_TOKEN;
        try {
            redisTemplate.opsForHash().put(goodsToken + seckillId + "_" + goodsId,
                    userToken + seckillId + "_" + goodsId + "_" + createOrderDto.getUserId(),"token");
        } catch (Exception e) {
            log.error("创建令牌出现异常,异常原因为" + e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public void addUserLock(Long userId){
        redisTemplate.opsForValue().set(RedisConstants.USER_LOCK + userId, RedisConstants.USER_LOCK, 5, TimeUnit.HOURS);
    }
    public boolean tryUserLock(Long userId){
        String lock = redisTemplate.opsForValue().get(RedisConstants.USER_LOCK + userId);
        return Strings.isBlank(lock);
    }

}
